import React, { useState } from "react"
import { Button, message, PageHeader, Table, Tag, Divider, Popconfirm, Modal, Upload } from "antd";
import { ArrowLeftOutlined, PlusOutlined, ExclamationCircleOutlined, UploadOutlined, LoadingOutlined, ClockCircleOutlined } from "@ant-design/icons";
import cs from "classnames";
import SearchAutoComplete from "libs/search-auto-complete"
import { useRequest } from '@umijs/hooks'
import { pageSetting, HOST, orderType } from "project-config"
import { useTableCheck, formatResult } from "../../shared/libs/hooks/table-hooks"
import { get } from "server"
import { del, putJSON } from "../../shared/server"

import { clearner } from "../../shared/libs/utils"
import highlight from "../../shared/libs/highlight";

const { confirm } = Modal;

const Salesman = (props) => {

	const onDelete = (id) => {
		del(`/management/account/salesman/${id}`).then((data) => {
			if (data) {
				message.success('删除成功')
				onSearch()
			}
		})
	}

	const enableAccount = (row) => {
		putJSON(`/management/account/salesman/${row.enabled ? "disable" : "enable"}/${row.id}`).then((data) => {
			if (data) {
				message.success(data.enabled ? "启用成功" : "禁用成功")
				onSearch()
			}
		})
	}

	const updateAccount = (id) => {
		props.history.push(`/app/account/salesman/edit/${id}`)
	}

	const resetPassword = (id) => {
		putJSON(`/management/account/salesman/reset/${id}`).then((data) => {
			if (data) {
				message.success("重置密码成功")
				onSearch()
			}
		})
	}

	//获取数据
	const getPageData = ({ current, pageSize, sorter, filters, searchKey }) => {
		let enabled;
		if (filters && filters.enabled && filters.enabled.length === 1) {
			enabled = filters.enabled[0];
		}
		let sortKey;
		let sortType;
		if (sorter && sorter.columnKey && sorter.order) {
			sortKey = sorter.columnKey;
			sortType = orderType[sorter.order];
		}
		return get(`/management/account/salesman/${pageSize}/${current}`, clearner({
			searchKey,
			sortType,
			sortKey,
			enabled
		}))
	}

	//表格选中
	const { rowSelection, items } = useTableCheck({})

	const { tableProps, params, refresh, pagination } = useRequest(
		getPageData, {
		paginated: true,
		defaultPageSize: 10,
		formatResult
	}
	)

	const onSearch = (searchKey) => {
		params[0].searchKey = searchKey
		refresh().finally()
	}

	const onDeleteBatch = () => {
		if (items != null) {
			del(`/management/account/salesman/batch/${items.join(',')}`).then(result => {
				if (result) {
					message.success(`成功删除 ${items.length} 条用户`)
					onSearch()
				}
			})
		}
	}

	const onEnabledBatch = () => {
		if (items != null) {
			putJSON(`/management/account/salesman/batch/enable/${items.join(',')}`).then(result => {
				if (result) {
					message.success(`成功启用 ${items.length} 条用户`)
					onSearch()
				}
			})
		}
	}

	const onDisabledBatch = () => {
		if (items != null) {
			putJSON(`/management/account/salesman/batch/disable/${items.join(',')}`).then(result => {
				if (result) {
					message.success(`成功禁用 ${items.length} 条用户`)
					onSearch()
				}
			})
		}
	}

	const showConfirm = (handle) => {
		const batchMapping = {
			Delete: {
				key: "删除",
				func: onDeleteBatch
			},
			Enabled: {
				key: "启用",
				func: onEnabledBatch
			},
			Disabled: {
				key: "禁用",
				func: onDisabledBatch
			},
		}
		confirm({
			title: `确认${batchMapping[handle].key}`,
			icon: <ExclamationCircleOutlined />,
			content: `确认要${batchMapping[handle].key}以下${items.length}记录?`,
			onOk() {
				batchMapping[handle].func();
			},
			onCancel() { },
		});
	}

	const salesmanColumns = [{
		title: '登录名',
		key: 'loginName',
		dataIndex: 'loginName',
		render: (v) => highlight(v, params[0].searchKey)
	}, {
		title: '姓名',
		key: 'name',
		dataIndex: 'name',
		render: (v) => highlight(v, params[0].searchKey)
	}, {
		title: '手机号',
		key: 'phoneNo',
		dataIndex: 'phoneNo',
		render: (v) => highlight(v, params[0].searchKey)
	}, {
		title: '状态',
		key: 'enabled',
		dataIndex: 'enabled',
		filters: [
			{ text: "启用", value: true },
			{ text: "禁用", value: false }
		],
		render: (text) => text ? <Tag color="#4CAF50" className={'large'}>启用中</Tag> : <Tag className={'large'} color="#f50">禁用中</Tag>
	}, {
		title: '最后登录时间',
		key: 'lastLoginTime',
		dataIndex: 'lastLoginTime',
		sorter: true,
		showSorterTooltip: false,
		sortDirections: ['ascend', 'descend', 'ascend'],
		render: (text) => text && <Tag className="large"><ClockCircleOutlined /> {text}</Tag>
	}, {
		title: '创建时间',
		key: 'createTime',
		dataIndex: 'createTime',
		sorter: true,
		showSorterTooltip: false,
		sortDirections: ['ascend', 'descend', 'ascend'],
		render: (text) => text && <Tag className="large"><ClockCircleOutlined /> {text}</Tag>
	}, {
		title: '备注',
		key: 'remarks',
		dataIndex: 'remarks',
	}, {
		title: '操作',
		key: 'action',
		render: (_, record) => {
			return (
				<>
					<a onClick={() => updateAccount(record.id)}>编辑</a>
					<Divider type="vertical" />
					<Popconfirm
						title={`确定要${record.enabled ? "禁用" : "启用"}此账号吗?`}
						placement="rightBottom"
						onConfirm={() => enableAccount(record)}
					>
						<a>{record.enabled ? "禁用" : "启用"}</a>
					</Popconfirm>
					<Divider type="vertical" />
					<Popconfirm
						title={`确定要重置密码吗，重置后将为初始密码?`}
						placement="rightBottom"
						onConfirm={() => resetPassword(record.id)}
					>
						<a>重置密码</a>
					</Popconfirm>
					<Divider type="vertical" />
					<Popconfirm
						title="确定要注销此账号吗?"
						placement="rightBottom"
						onConfirm={() => onDelete(record.id)}
					>
						<a>注销</a>
					</Popconfirm>
				</>
			)
		}
	}]

	const [loading, setLoading] = useState(false);

	const onFileChange = ({ file }) => {
		const { response } = file;
		setLoading(true);
		if (!response) {
			setLoading(true);
			return;
		}
		message.success("导入成功")
		setLoading(false);
		refresh().finally()
	}

	const btnPrpos = {
		type: 'primary',
		disabled: items.length < 1,
		ghost: true,
		style: { marginLeft: 10 }
	}

	return (
		<div className={'zr-panel'}>
			<div className={'zr-panel-header'}>
				<PageHeader
					backIcon={<ArrowLeftOutlined />}
					onBack={() => window.history.back()} title='业务员管理'
					subTitle=''
				/>
			</div>
			<div className={'zr-list-page-box body-bg body-border absolute'}>
				<div className={cs('zr-query-box')} style={{ paddingRight: '20px' }}>
					<SearchAutoComplete style={{marginRight: 10}} allowClear={true} onSelect={onSearch} placeholder="登录名/手机号/姓名查询" />
					<Button
						style={{marginLeft: 10}}
						type="primary"
						onClick={() => props.history.push("/app/account/salesman/add")}>
						<PlusOutlined />添加业务员
					</Button>
					<Upload
						accept=".xls,.xlsx"
						name='file'
						action={`${HOST}/management/account/salesman/import`}
						multiple={false}
						withCredentials={true}
						showUploadList={false}
						onChange={onFileChange}
					>
						<Button type="primary" style={{ marginLeft: 10 }}>{loading ? <LoadingOutlined /> : <UploadOutlined />} 批量导入 </Button>
					</Upload>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Enabled")}
					>
						批量启用
					</Button>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Disabled")}
					>
						批量禁用
					</Button>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Delete")}
						danger
					>
						批量删除
					</Button>
					
				</div>
				<div className={'zr-table-box'}>
					<Table
						{...tableProps}
						pagination={{
							...pagination,
							...pageSetting
						}}
						rowSelection={rowSelection}
						rowKey={record => record.id}
						size='middle'
						columns={salesmanColumns} />
				</div>
			</div>
		</div>
	)
}

export default Salesman